import { onMounted, ref } from 'vue';

export const initMapHook = () => {
  const initMap = ref(null);

  onMounted(() => {
    const key = import.meta.env.VITE_TDTKEY;
    const TiandiMap_vect = new ol.layer.Tile({
      title: '天地图矢量图层',
      source: new ol.source.XYZ({
        url: 'http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=' + key,
        wrapX: false,
        crossOrigin: 'anonymous',
      }),
    });

    const TiandiMap_vectcia = new ol.layer.Tile({
      title: '天地图矢量注记图层',
      source: new ol.source.XYZ({
        url: 'http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' + key,
        wrapX: false,
        crossOrigin: 'anonymous',
      }),
    });

    const TiandiMap_img = new ol.layer.Tile({
      title: '天地图影像图层',
      source: new ol.source.XYZ({
        url: 'http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + key,
        wrapX: false,
        crossOrigin: 'anonymous',
      }),
    });
    const TiandiMap_imgcia = new ol.layer.Tile({
      title: '天地图影像注记图层',
      source: new ol.source.XYZ({
        url: 'http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=' + key,
        wrapX: false,
        crossOrigin: 'anonymous',
      }),
    });

    // 矢量+注记图层组
    const vecLayergroup = new ol.layer.Group({
      layers: [TiandiMap_vect, TiandiMap_vectcia],
      visible: false, //图层不可见
    });
    // 影像+注记图层组
    const imgLayergroup = new ol.layer.Group({
      layers: [TiandiMap_img, TiandiMap_imgcia],
      visible: false, //图层不可见
    });

    initMap.value = new ol.Map({
      target: 'map',
      view: new ol.View({
        projection: 'EPSG:4326',
        center: [114.38, 30.49],
        zoom: 13,
      }),
      layers: [imgLayergroup, vecLayergroup, TiandiMap_vect],
    });
  });
  return { initMap };
};
